import { getItem } from '@/utils/local';
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path:'/',
    redirect:'/login'
  },
  {
    path:'/index',
    name:'index',
    component:()=>import('@/pages/index.vue'),
    children:[
      {path:'/home',name:'home',component:()=>import('@/pages/home.vue')},
      {path: '/create', name: 'create', component: () => import('@/pages/create.vue'),},
      {path: '/self', name: 'self', component: () => import('@/pages/self.vue'),},
      {path: '/articleDetails', name: 'articleDetails', component: () => import('@/pages/articleDetails.vue'),},
      {path: '/homePage', name: 'homePage', component: () => import('@/pages/homePage.vue'),},
      {path: '/tags', name: 'tags', component: () => import('@/pages/tags.vue'),},
      {path: '/topic', name: 'topic', component: () => import('@/pages/topic.vue'),},
      {path: '/search', name: 'search', component: () => import('@/pages/search.vue'),},
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/pages/login/Login.vue'),
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/pages/register/Register.vue'),
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

router.beforeEach((to, from, next) => {
  if (to.path == '/login' || to.path == '/register') {
      // 登录或者注册才可以往下进行
      next();
  } else {
      // 获取 token
      const token = getItem('token'); 
      // token 不存在
      if (token === null || token === '') {
        window.$message.error('您还没有登录，请先登录')
          next('/login');
      } else {
          next();
      }
  }
});



export default router
